package hn.cch.security.controller;

import hn.cch.security.util.VerifyCodeUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;

/**
 * @author CCH
 * @version 2018.09.25
 */

@Controller(value = "")
public class LoginController {

    @RequestMapping(value = "/login")
    public String login() {
        return "login";
    }

    @RequestMapping(value = "/images/verifycode")
    public String verifycode(HttpServletRequest request, HttpServletResponse
            response)
            throws Exception {
        OutputStream os = response.getOutputStream();
        Map<String, Object> map = VerifyCodeUtil.getVerifyCode(60, 20);


        request.getSession().setAttribute("code", map.get("code").toString()
                .toLowerCase());
        request.getSession().setAttribute("time", new Date().getTime());

        ImageIO.write((BufferedImage) map.get("image"), "JPEG", os);

        return null;
    }

    @RequestMapping(value = "/checkcode")
    @ResponseBody
    public String checkcode(HttpServletRequest request, HttpSession session)
            throws Exception {
        String checkCode = request.getParameter("checkCode");
        Object cko = session.getAttribute("code"); //验证码对象
        if (cko == null) {
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "验证码已失效，请重新输入！";
        }

        String captcha = cko.toString();
        Date now = new Date();
        Long codeTime = Long.valueOf(session.getAttribute("time") + "");
        if (StringUtils.isEmpty(checkCode) || captcha == null || !(checkCode
                .equalsIgnoreCase(captcha))) {
            request.setAttribute("errorMsg", "验证码错误！");
            return "验证码错误！";
        } else if ((now.getTime() - codeTime) / 1000 / 60 > 5) {//验证码有效时长为5分钟
            request.setAttribute("errorMsg", "验证码已失效，请重新输入！");
            return "验证码已失效，请重新输入！";
        } else {
            session.removeAttribute("code");
            return "1";
        }
    }

}
